package com.ncs.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ncs.entity.Result;
import com.ncs.pojo.Reservation;
import com.ncs.service.ReservationService;
import com.ncs.utils.SMSUtils;
import com.ncs.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@Slf4j
public class ReservationController {


    @Autowired
    private ReservationService reservationService;
    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestBody Reservation reservation, HttpSession session){
        Result result = new Result();
        //获取手机号
        String phone=reservation.getPhone();
        if(!StringUtils.isEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //也可以将自定义信息存入code发送给用户
            //String code = "您已成功预定："+reservation.getTableId()+"号餐桌，共："+reservation.getCllentNumber()+"人,预定时间为："+reservation.getDatetime();
            log.info("code={}",code);
            //调用阿里云提供的短信服务API完成发送短信,要省钱先注释。（已测试可用）
            SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);

            //将生成的验证码保存到Session
            session.setAttribute(phone,code);
            result.setFlag(true);
            result.setMessage("手机短信发送成功");
            return result;
        }
        result.setFlag(false);
        result.setMessage("手机短信发送失败");
        return result;
    }

    @PostMapping("/login")
    public Result login(@RequestBody Map map, HttpSession session) {
        Result result = new Result();
        log.info("map:{}", map.toString());
        //获取手机号
        String phone = map.get("phone").toString();
        String name = map.get("name").toString();
        String datetime = map.get("datetime").toString();
        Date date = new Date(datetime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");


        int cllentNumber = (int)map.get("cllentNumber");
        int tableId = (int)map.get("tableId");
        //获取验证码
        String code = map.get("code").toString();
        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //从redis中获取缓存的验证码
        //Object codeInSession = redisTemplate.opsForValue().get(phone);
        //进行验证码比对（页面提交的验证码和Session中保存的验证码比对）
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Reservation::getPhone, phone);
            Reservation reservation = reservationService.getOne(queryWrapper);
            if (reservation == null) {
                //判断当前手机号是否为新用户，如果是新用户则自动完成注册
                reservation = new Reservation();
                reservation.setName(name);
                reservation.setPhone(phone);
                reservation.setDatetime(date);
                reservation.setCllentNumber(cllentNumber);
                reservation.setTableId(tableId);
                reservationService.save(reservation);
            }
            //session.setAttribute("",reservation.getId());
            //如果用户登录成功，删除redis中缓存的验证码
            //redisTemplate.delete(phone);
            result.setFlag(true);
            result.setMessage("预定成功");
            return result;
        }
        result.setFlag(true);
        result.setMessage("预定失败");
        return result;
    }


}
